<template>
	<view class="info">
		<!-- 个人信息界面 -->
		<!-- 头像 -->
		<view class="infoitem" @click="getimage">
			<text class="txx">头像</text>
			<view class="right">
				<u-avatar v-if="userInfos.avatar" :src="userInfos.avatar|avatarImage" fontSize="10"></u-avatar>
				<u-avatar v-else :src="defaultImag" fontSize="10"></u-avatar>
				<text class="dyy">></text>
			</view>
		</view>
		<u-modal :show="showMd" @confirm="confirm" ref="uModal" :asyncClose="true">

			<u-input v-if="modelflag=='username'" placeholder="请输入昵称" border="surround" v-model="userInfos.username">
				<template #prefix>
					<u--text text="昵称" margin="0 3px 0 0" type="tips"></u--text>
				</template>

			</u-input>

			<u-input v-else-if="modelflag=='phone'" placeholder="请输入电话" border="surround"
				v-model="userInfos.phone"><u--text text="电话" slot="prefix" margin="0 3px 0 0"
					type="tips"></u--text></u-input>
			<u-input v-else-if="modelflag=='idcard'" placeholder="请输入身份证" border="surround"
				v-model="userInfos.identityCard"><u--text text="身份证" slot="prefix" margin="0 3px 0 0"
					type="tips"></u--text></u-input>
			<u-input v-else="modelflag=='email'" placeholder="请输入邮箱" border="surround"
				v-model="userInfos.email"><u--text text="邮箱" slot="prefix" margin="0 3px 0 0"
					type="tips"></u--text></u-input>

		</u-modal>
		<!-- 昵称 -->
		<view class="infoitem" @click="showMO('username')">
			<text class="txx">昵称</text>
			<view class="right">

				<text class="dyy">{{userInfos.username}}</text>
				<text class="dyy">></text>
			</view>
		</view>
		<!-- 手机号 -->
		<view class="infoitem" @click="showMO('phone')">
			<text class="txx">手机号</text>
			<view class="right">
				<text class="dyy" v-if="userInfos.phone">{{userInfos.phone}}</text>
				<text class="dyy" v-else>请绑定电话</text>
				<text class="dyy">></text>
			</view>
		</view>
		<!-- 微信账号 -->
		<view class="infoitem" @click="showMO('idcard')">
			<text class="txx">身份证号</text>
			<view class="right">
				<text class="dyy" v-if="userInfos.identityCard">已绑定</text>
				<text class="dyy" v-else>未绑定</text>
				<text class="dyy">></text>
			</view>
		</view>
		<!-- QQ邮箱 -->
		<view class="infoitem" @click="showMO('email')">
			<text class="txx">QQ邮箱</text>
			<view class="right">

				<text class="dyy" v-if="userInfos.email">{{userInfos.email}}</text>
				<text class="dyy" v-else>请绑定邮箱</text>
				<text class="dyy">></text>
			</view>
		</view>
		<!-- 生日 -->
		<view class="infoitem" @click="birthdayClick">
			<text class="txx">生日</text>
			<view class="right">
				<text class="dyy" v-if="userInfo.birthday">{{userInfo.birthday}}</text>
				<text class="dyy" v-else>请选择生日</text>

				<text class="dyy">></text>

				<u-datetime-picker :closeOnClickOverlay="true" @close="close" @cancel="close" @confirm="quere"
					:show="show" v-model="value1" mode="date"></u-datetime-picker>
			</view>
		</view>
		<!-- 性别 -->
		<view class="infoitem" @click="sexClick">
			<text class="txx">性别</text>
			<view class="right">
				<text class="dyy">{{userInfo.sex}}</text>
				<text class="dyy">></text>
				<u-picker :show="showSex" :columns="columns" :closeOnClickOverlay="true" @close="sexClose"
					@cancel="sexClose" @confirm="sexConfirm"></u-picker>

			</view>
		</view>

		<view class="bc" @click="bacsuiji">
			<u-button type="primary" shape="circle">保存</u-button>
		</view>


	</view>
</template>

<script>
	/**
	 * 个人信息界面
	 */
	import {
		mapActions,
		mapGetters
	} from 'vuex';
	import {
		base_Url
	} from '../../utils/Url';

	const sexSelect = ["男", "女", "未知"]
	export default {
		data() {
			return {
				defaultImagL: base_Url + "/upload/defaultimg.jpg",
				modelflag: '',
				showMd: false,
				src: "", //头像
				show: false, //生日
				showSex: false, //性别
				userInfo: {
					birthday: '选择',
					sex: "未知",

				},
				userInfos: {},
				columns: [
					['未知', '男', '女']
				],
				value1: Number(new Date())
			}
		},
		onShow() {
			const today = new Date();
			const todayStr = today.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
			// console.log('时间', typeof todayStr);
			this.userInfo.birthday = todayStr
		},
		onLoad(options) {


			const aa = uni.getStorageSync("userinfo")
			if (aa) {
				// console.log('用户信息', aa);
				this.userInfos = JSON.parse(aa)
				const date = new Date(JSON.parse(aa).birthday);

				// 使用 Intl.DateTimeFormat 来格式化为 yyyy-MM-dd
				const formattedDate = new Intl.DateTimeFormat('en-CA').format(date);

				this.userInfo.birthday = formattedDate
				this.userInfo.sex = sexSelect[JSON.parse(aa).sex]
			} else {
				this.userInfos = {}
			}
			// const message = decodeURIComponent(options.name);  // 手动解码
			// console.log(message);
			// var data = options.id;
			// // console.log(data)
			// var that = this;

			// // 页面加载时，检查是否有缓存的图片路径
			// uni.getStorage({
			// 	key: 'cachedImagePath',
			// 	success: function(res) {
			// 		console.log('获取到缓存的图片路径：', res.data);
			// 		that.src = res.data; // 如果有缓存的路径，显示图片
			// 	},
			// 	fail: function() {
			// 		console.log('没有缓存的图片');
			// 	}
			// });
			// uni.getStorageInfo({
			// 	success: function(res) {
			// 		console.log('本地存储的总大小: ', res.currentSize, '字节');
			// 		console.log('本地存储的限制大小: ', res.limitSize, '字节');
			// 	},
			// 	fail: function(err) {
			// 		console.log('获取存储信息失败:', err);
			// 	}
			// });


		},
		filters: {
			avatarImage(e) {
				// console.log('头像', JSON.parse(JSON.parse(e)).url);
				try {
					return JSON.parse(e).url
					// return true
				} catch (error) {
					// return false
					return e.url || e
				}
			}
		},
		methods: {
			...mapActions(['GetuserInfo', 'Logout']),
			updateAvatar(e) {
				console.log('图片', e);
			},
			bacsuiji() {

				console.log('随即', this.userInfos.avatar);
				let avatar = {};
				// console.log('随即2', JSON.stringify(JSON.parse(this.userInfos.avatar)));
				if (this.userInfos.avatar != null) {
					if (this.userInfos.avatar.name) {
						avatar = this.userInfos.avatar
						console.log(11, avatar);
						avatar = JSON.stringify(avatar)
					} else {
						avatar = this.userInfos.avatar
					}
				} else {
					avatar = null
				}


				this.$http
					.put('/wxUser/update', {
						id: this.userInfos.id,
						birthday: this.userInfo.birthday,
						sex: sexSelect.indexOf(this.userInfo.sex),
						username: this.userInfos.username,
						phone: this.userInfos.phone,
						email: this.userInfos.email,
						identityCard: this.userInfos.identityCard ? this.userInfos.identityCard : "",
						avatar: avatar
					})
					.then((res) => {
						console.log('res', res)
						if (res.code === 200) {
							// this.$message.success('修改成功')
							// const that = this
							uni.$showMsg("修改成功");
							const {
								GetuserInfo
							} = this
							// console.log('this', this);
							// console.log('that', that);
							// this.$emit('ok')
							GetuserInfo().then(userDetails => {
								// console.log('用户信息', JSON.parse(userDetails.avatar));
								// that.$set(that.userInfos, 'avatar', JSON.parse(userDetails.avatar)); // Update the username
							})
						}
						if (res.code == 500) {
							const {
								Logout
							} = this
							Logout().then(res => {
								console.log('退出登录', res);
								uni.reLaunch({
									url: "/pages/My/My"
								})
							})
						}
					})
			},
			showMO(e) {
				console.log('参数', e);
				this.showMd = true
				this.modelflag = e
			},
			confirm() {
				this.showMd = false
			},
			// 相机
			getimage(e) {
				// console.log('突变', e);

				var that = this
				uni.chooseImage({
					count: 1, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: function(res) {
						console.log(JSON.stringify(res));
						uni.uploadFile({
							url: base_Url + '/common/upload', // 这里替换为你要上传到的服务器接口地址
							filePath: res.tempFilePaths[0], // 选中的文件路径
							name: 'file', // 后端接收文件的字段名，通常为 'file' 或根据实际情况修改
							// formData: {
							//     // 可以添加其他需要上传的数据
							//     userId: '12345', // 假设你要上传用户ID等其他字段
							// },
							success: function(uploadRes) {
								console.log('上传成功:', uploadRes);
								const data = JSON.parse(uploadRes.data); // 假设返回的数据是JSON格式
								if (data.code = 200) {
									console.log('daxinxi', that.userInfos);
									// 上传成功后做一些处理，比如更新头像URL
									console.log('that', that);

									// that.$set(that.userInfos, 'avatar', '');
									that.$set(that.userInfos, 'avatar', data.result[0]);



								}
							},
							fail: function(error) {
								console.error('上传失败:', error);
							}
							// that.src = res.tempFilePaths
							//缓存图片
							// uni.setStorage({
							// 	key: 'cachedImagePath',
							// 	data: res.tempFilePaths[0],
							// 	success: function() {
							// 		console.log('图片缓存成功');
							// 	}
							// });
						});
					}
				});
				// 将图片路径缓存到本地存储中




			},
			// 生日
			birthdayClick() {
				if (!this.show) {
					this.show = true
				}

			},
			close() {
				// console.log("关闭页面"+!this.show);
				if (this.show) {
					this.show = !this.show
				}

			},
			async quere(e) {
				console.log(e);
				if (this.show) {
					const timeFormat = uni.$u.timeFormat;
					this.userInfo.birthday = await timeFormat(e.value, 'yyyy-mm-dd');

					this.show = false
				}
			},
			// 性别
			sexClick() {
				if (!this.showSex) {
					this.showSex = true
				}

			},
			sexClose() {
				// console.log('xianshi ', this.showSex);
				if (this.showSex) {
					this.showSex = false
				}
			},
			sexConfirm(e) {

				console.log(e.value[0]);
				this.userInfo.sex = e.value[0]
				this.showSex = false

			}

		}
	}
</script>

<style lang="less">
	.info {
		background-color: #f6f6f6;
		// background-color: #1979f6;
		height: 600px;

		.infoitem {
			margin-top: 2px;
			border-radius: 8px;
			background-color: #ffffff;
			padding: 8px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.txx {
				font-size: 18px;
				font-weight: bold;
			}

			.right {
				display: flex;
				align-items: center;

				.dyy {
					margin-left: 4px;
					font-size: 18px;
					color: #adadad;
				}

			}
		}

		.bc {
			margin-top: 20px;
		}
	}
</style>